package com.rickpan.service;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;

/**
 * 邮件服务
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class EmailService {

    private final JavaMailSender mailSender;

    @Value("${spring.mail.username}")
    private String fromEmail;

    @Value("${app.name:RickPan}")
    private String appName;

    /**
     * 发送密码重置验证码邮件
     */
    public void sendPasswordResetCode(String toEmail, String code) {
        try {
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");

            helper.setFrom(fromEmail);
            helper.setTo(toEmail);
            helper.setSubject(appName + " - 密码重置验证码");

            String htmlContent = buildPasswordResetEmailContent(code);
            helper.setText(htmlContent, true);

            mailSender.send(message);
            log.info("密码重置验证码邮件发送成功: {}", toEmail);

        } catch (MessagingException e) {
            log.error("发送密码重置验证码邮件失败: {}", toEmail, e);
            throw new RuntimeException("邮件发送失败", e);
        }
    }

    /**
     * 构建密码重置邮件内容
     */
    private String buildPasswordResetEmailContent(String code) {
        return String.format("""
            <!DOCTYPE html>
            <html>
            <head>
                <meta charset="UTF-8">
                <title>密码重置验证码</title>
                <style>
                    body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; }
                    .container { max-width: 600px; margin: 0 auto; padding: 20px; }
                    .header { background: linear-gradient(135deg, #667eea 0%%, #764ba2 100%%); color: white; padding: 30px; text-align: center; border-radius: 10px 10px 0 0; }
                    .content { background: #f9f9f9; padding: 30px; border-radius: 0 0 10px 10px; }
                    .code-box { background: white; border: 2px dashed #667eea; padding: 20px; text-align: center; margin: 20px 0; border-radius: 8px; }
                    .code { font-size: 32px; font-weight: bold; color: #667eea; letter-spacing: 8px; }
                    .warning { background: #fff3cd; border: 1px solid #ffeaa7; padding: 15px; border-radius: 5px; margin: 20px 0; }
                    .footer { text-align: center; margin-top: 30px; color: #666; font-size: 12px; }
                </style>
            </head>
            <body>
                <div class="container">
                    <div class="header">
                        <h1>🔐 密码重置验证码</h1>
                        <p>您正在重置 %s 账户密码</p>
                    </div>
                    <div class="content">
                        <p>您好！</p>
                        <p>我们收到了您的密码重置请求。请使用以下验证码来重置您的密码：</p>

                        <div class="code-box">
                            <div class="code">%s</div>
                        </div>

                        <div class="warning">
                            <strong>⚠️ 安全提醒：</strong>
                            <ul>
                                <li>验证码有效期为 <strong>10分钟</strong></li>
                                <li>请勿将验证码告诉他人</li>
                                <li>如果这不是您的操作，请忽略此邮件</li>
                            </ul>
                        </div>

                        <p>如果您没有请求重置密码，请忽略此邮件。您的账户安全不会受到影响。</p>

                        <p>感谢您使用 %s！</p>
                    </div>
                    <div class="footer">
                        <p>此邮件由系统自动发送，请勿回复</p>
                        <p>© 2024 %s. All rights reserved.</p>
                    </div>
                </div>
            </body>
            </html>
            """, appName, code, appName, appName);
    }

    /**
     * 发送简单文本邮件（备用方案）
     */
    public void sendSimplePasswordResetCode(String toEmail, String code) {
        try {
            SimpleMailMessage message = new SimpleMailMessage();
            message.setFrom(fromEmail);
            message.setTo(toEmail);
            message.setSubject(appName + " - 密码重置验证码");
            message.setText(String.format(
                "您的密码重置验证码是：%s\n\n" +
                "验证码有效期为10分钟，请及时使用。\n" +
                "如果这不是您的操作，请忽略此邮件。\n\n" +
                "感谢您使用 %s！", 
                code, appName
            ));

            mailSender.send(message);
            log.info("简单密码重置验证码邮件发送成功: {}", toEmail);

        } catch (Exception e) {
            log.error("发送简单密码重置验证码邮件失败: {}", toEmail, e);
            throw new RuntimeException("邮件发送失败", e);
        }
    }
}
